/**
 * Created by Dalyn on 2017/3/3.
 */
import React from 'react';
import EventManager from '../util/EventManager.js';
import {hashHistory, Link} from 'react-router';
import Relay from "react-relay";
import Confirm from "../common/Confirm.js";
import InputBox from "../common/InputBox";
import MsLoginMutation from "./mutation/MsLoginMutation.js"
import SaveUserToken from "./mutation/SaveUserToken"

export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            /*账号密码正确*/
            flag: true,
            /*是否进入 选择企业账户页面*/
            isAccount: true,
            title: '欢迎登录衣有道系统',
            is: true
        }
        this.style = {
            username: {
                width: "236px",
                height: "40px",
                borderColor: "#bbbbbb",
                marginTop: "15px"
            },
            password: {
                width: "236px",
                height: "40px",
                borderColor: "#bbbbbb",
                marginTop: "15px"
            },
            confirm: {
                width: '256px',
                height: '42px',
                backgroundColor: "#a0d468",
                fontSize: "18px",
                color: "#fff",
                marginTop: "16px",
                fontFamily: "Microsoft YaHei"
            }
        };
        this.isshow = 'none';
    }

    componentWillMount() {

        if (this.props.params.channel == 'password') {
            this.setState({
                title: '重置密码成功，请重新登录'
            });
        }
    }

    componentDidMount() {
        let strCookie = document.cookie;
        let arrCookie = strCookie.split("; ");
        let username = '';
        let password = '';
        for (let i = 0; i < arrCookie.length; i++) {
            let arr = arrCookie[i].split("=");
            if ("username" == arr[0]) {
                username = arr[1];
                continue;
            }
            if ("password" == arr[0]) {
                password = arr[1];
                continue;
            }
        }
        if (username.length > 0 && password.length > 0) {

            this.refs.username.setState({
                text: username
            })
            this.refs.password.setState({
                text: password
            });
            this.refs.label.checked = true;
        }
    }


    bluron(type) {
        this.refs.username.setState({
            errorhint: ''
        });
        this.refs.password.setState({
            errorhint: ''
        });
        let username = this.refs.username.state.text;
        let password = this.refs.password.state.text;
        switch (type) {
            case "username":
                if (username.length != 11) {
                    this.isshow = 'block'
                    this.refs.username.setState({
                        errorhint: '格式不正确'
                    });

                    this.setState({
                        is: 'false'
                    });
                } else {

                    this.refs.username.setState({
                        errorhint: ''
                    });
                }

                return;

            case "password":

                if (password.length > 5 || password.length < 33) {
                    this.refs.password.setState({
                        errorhint: ''
                    });
                }
                return;
        }
    }

    login(is) {
        if (this.refs.username.state.errorhint.text || this.refs.password.state.errorhint.text) {
            return
        }

        this.refs.username.setState({
            errorhint: ''
        });

        this.refs.password.setState({
            errorhint: ''
        });

        let username = this.refs.username.state.text;

        let password = this.refs.password.state.text;
        if (username == '') {
            this.isshow = 'block'
            this.refs.username.setState({
                errorhint: '用户名不能为空'
            });
            this.setState({
                is: !is
            });
            return
        }


        if (password == '') {
            this.isshow = 'block'
            this.refs.password.setState({
                errorhint: '密码不能为空'
            });
            this.setState({
                is: !is
            });
            return
        }

        Relay.Store.commitUpdate(
            new MsLoginMutation({
                phone: username,
                password: password,

            }),
            {
                onFailure: () => {
                    alert('请求失败');
                },
                onSuccess: (response) => {
                    /*返回的错误码*/
                    let errorCode = response.msLogin.loginResponse.errorCode;
                    let value = response.msLogin.loginResponse.value;
                    let msToken = response.msLogin.loginResponse.token;
                    let manager = response.msLogin.loginResponse.manager;
                    let msUid = '';
                    let roleId = '';
                    if (null != manager) {
                        msUid = manager.managerId;
                        roleId = manager.roleId;
                    }
                    if (errorCode == 0) {

                        if (this.refs.label.checked) {
                            document.cookie = "username=" + username;
                            document.cookie = "password=" + password;
                        } else {
                            document.cookie = "username=";
                            document.cookie = "password=";
                        }
                        // EventManager.emitter('islogin', true);
                        // hashHistory.push('/homepage');
                        sessionStorage.setItem('msUserName', manager.name);
                        sessionStorage.setItem('msUid', manager.managerId);
                        sessionStorage.setItem('msToken', msToken);
                        let pId = response.msLogin.loginResponse.manager.pid;
                        if (pId != '' && pId != undefined && pId != null) {
                            sessionStorage.setItem('pIds', pId);
                        }
                        Relay.Store.commitUpdate(
                            new SaveUserToken({
                                type: '0',
                                userId: msUid
                            }),
                            {
                                onFailure: () => {

                                },
                                onSuccess: (response) => {
                                    //debugger
                                    let errorCode = response.saveUserToken.saveUserToken.errorCode;
                                    let token = response.saveUserToken.saveUserToken.token;
                                    let uid = response.saveUserToken.saveUserToken.userId;
                                    if (errorCode == 0) {
                                        hashHistory.push('/');
                                        EventManager.emitter('islogin', true);
                                    }
                                }
                            }
                        )
                    } else if (errorCode == 100001) {
                        this.isshow = 'block';
                        this.refs.password.setState({
                            errorhint: value
                        });
                        this.setState({
                            is: !is
                        });
                    } else {
                        this.isshow = 'block';
                        this.refs.username.setState({
                            errorhint: value
                        });
                        this.setState({
                            is: !is
                        });
                    }

                }
            }
        )
    }

    render() {
        return (
            <div style={Style.box}>
                <p style={Style.p}>{this.state.title}</p>
                <InputBox style={this.style.username} defaultvalute="请输入用户名" ref={'username'} maxlength={11}
                          bluron={this.bluron.bind(this, "username")} errorhint={this.isshow} isloginintext={true}/>
                <InputBox style={this.style.password} defaultvalute="请输入密码" type={'password'} errorhint={this.isshow}
                          ref={'password'} bluron={this.bluron.bind(this, "username")} isloginintext={true}
                          maxlength={32}/>
                <div style={Style.check} className="clear">
                    <label htmlFor="check" style={Style.label}><input id="check" type="checkbox" name="check"
                                                                      style={Style.input} ref={'label'}/>记住密码</label>
                </div>
                <Confirm style={this.style.confirm} tcontext={'登 录'}
                         touch={this.login.bind(this, this.state.is)}/>
            </div>
        );
    }
}

var Style = {
    box: {
        width: "259px",
        height: "329px",
        margin: "0 auto",
        padding: "10px 0"
    },
    p: {
        height: "18px",
        fontSize: "20px",
        textAlign: "center",
        lineHeight: "18px",
        verticalAlign: "middle",
        padding: "28px 0",
        margin: "0 auto",
        color: "#1b3249",
        fontFamily: "Microsoft YaHei"
    },
    check: {
        width: "256px",
        height: "13px",
        textAlign: "left",
        lineHeight: "13px",
        padding: "11px 0",
        margin: "0 auto",
    },
    label: {
        fontSize: "14px",
        vertical: "-align: -2px"
    },
    input: {
        width: "18px",
        height: "18px",
        verticalAlign: "-2px"
    },
    span: {
        float: "right",
        color: "#60caf1",
        fontSize: "14px",
    },
    span1: {
        float: "right",
        fontSize: "14px",
    },
    apply: {
        marginTop: "15px"
    }
}